# -*- coding: utf-8 -*
#!usr/bin/python
import datetime
import sqlite3
import time

import dht11
import RPi.GPIO as GPIO
from app import app

DATABASE = app.config['DATABASE']
# initialize GPIO
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.cleanup()

def create_database():
    conn = sqlite3.connect(DATABASE)
    create_tb_cmd = '''CREATE TABLE IF NOT EXISTS test
       (ID integer PRIMARY KEY autoincrement,
       temperature     varchar (10)  NOT NULL,
       humidity        varchar (10)  NOT NULL,
       createTime      varchar (50))'''
    conn.execute(create_tb_cmd)
    print ("Table created successfully")
    conn.commit()
    conn.close()


def insert_data(temperature, humidity, createTime):
       conn = sqlite3.connect(DATABASE)
       cur = conn.cursor()
       print ("Opened database successfully")
       sql = 'INSERT INTO test (temperature,humidity,createTime) VALUES (?,?,?)'
       val = (temperature, humidity, createTime)
       cur.execute(sql, val)
       conn.commit()
       print ("Records created successfully")
       conn.close()

def deal_data():
    # read data using pin 2
    instance = dht11.DHT11(pin=2)
    create_database()
    while True:
        result = instance.read()
        if result.is_valid():
            print("datetime: " + str(datetime.datetime.now()))
            print("Temperature: %d C" % result.temperature)
            print("Humidity: %d %%" % result.humidity)
            createTime = str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
            insert_data(result.temperature, result.humidity,createTime)
        time.sleep(5)
